import re
from collections import Counter
import jieba
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from PIL import Image
from wordcloud import WordCloud
from datetime import datetime
from gensim import corpora
from gensim.models import LdaModel
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection


class CommentAnalysis:
    def __init__(self, _text, _wordlist, _stopwords, _output_path, _show, _user_data):
        self._res = None
        self._text = _text
        self._wordlist = _wordlist
        self._stopwords = _stopwords
        self._output_path = _output_path
        self._show = _show
        self._user_data = _user_data

    # 情感分析
    def analyze_sentiment(self, text):
        analyzer = SentimentIntensityAnalyzer()
        sentiment_score = analyzer.polarity_scores(text)
        if sentiment_score['compound'] >= 0.05:
            return 'positive'
        elif sentiment_score['compound'] <= -0.05:
            return 'negative'
        else:
            return 'neutral'

    # LDA主题建模
    def lda_analysis(self, texts, num_topics=3):
        texts_cut = [[word for word in jieba.cut(text)] for text in texts]
        dictionary = corpora.Dictionary(texts_cut)
        corpus = [dictionary.doc2bow(text) for text in texts_cut]
        lda_model = LdaModel(corpus, num_topics=num_topics, id2word=dictionary)
        topics = lda_model.print_topics(num_words=5)
        return topics

    # 生成词云
    def generate_wordcloud(self, _background_path=None, _width=800, _height=500, _colormap=None):
        if _background_path is not None:
            _background = Image.open(_background_path)
            graph = np.array(_background)
        else:
            graph = None
        wordcloud = WordCloud(background_color='white',
                              font_path=r"./utils/fonts/simhei.ttf",
                              width=_width,
                              height=_height,
                              stopwords=self._stopwords,
                              mask=graph,
                              colormap=_colormap,
                              ).generate(self._text)
        image = wordcloud.to_image()
        wordcloud.to_file(self._output_path + "/wordcloud.png")
        self.remove_white_background(self._output_path + "/wordcloud.png", self._output_path + "/wordcloud.png")
        if self._show:
            image.show()

    # 去除白色背景
    def remove_white_background(self, input_img_path, output_img_path):
        img = Image.open(input_img_path)
        img = img.convert("RGBA")
        datas = img.getdata()
        newData = []
        for item in datas:
            if item[0] == 255 and item[1] == 255 and item[2] == 255:
                newData.append((255, 255, 255, 0))
            else:
                newData.append(item)
        img.putdata(newData)
        img.save(output_img_path, "PNG")

    # 根据用户评论的情感计算情感占比
    def emotion_calculate(self, wordlist):
        positive, negative, anger, disgust, fear, sad, surprise, good, happy = 0, 0, 0, 0, 0, 0, 0, 0, 0
        wordset = set(wordlist)
        for word in wordset:
            freq = wordlist.count(word)
            if word in self.Positive:
                positive += freq
            if word in self.Negative:
                negative += freq
            if word in self.Anger:
                anger += freq
            if word in self.Disgust:
                disgust += freq
            if word in self.Fear:
                fear += freq
            if word in self.Sad:
                sad += freq
            if word in self.Surprise:
                surprise += freq
            if word in self.Good:
                good += freq
            if word in self.Happy:
                happy += freq
        emotion_info = {
            'length': len(wordlist),
            'positive': positive,
            'negative': negative,
            'anger': anger,
            'disgust': disgust,
            'fear': fear,
            'good': good,
            'sadness': sad,
            'surprise': surprise,
            'happy': happy
        }
        indexs = ['length', 'positive', 'negative', 'anger', 'disgust', 'fear', 'good', 'sadness', 'surprise', 'happy']
        return pd.Series(emotion_info, index=indexs)

    # 情感分析并绘制柱状图
    def emotion_bar(self, _category=2):
        # 你之前的情感分类部分
        # 情感分类：正面、负面
        res = self.emotion_calculate(self._wordlist)
        self._res = res

        # 绘制情感柱状图
        self.draw_emotion_bar(res)
        return res.to_list()

    # 绘制情感柱状图
    def draw_emotion_bar(self, _res):
        # 设置不同情感的显示顺序和颜色
        order = ['happy', 'good', 'anger', 'sadness', 'fear', 'disgust', 'surprise']
        labels = ['happy', 'good', 'anger', 'sadness', 'fear', 'disgust', 'surprise']
        colors = ['#ffbf91', '#fffbb0', '#ff7a8a', '#abd4ff', '#dcabff', '#95a672', '#ff9ebe']

        _res = _res.reindex(order)
        sns.barplot(x=order, y=_res.values, order=order, palette=colors, alpha=0.7)
        for index, value in enumerate(_res):
            plt.text(index, value + 0.5, str(value), ha='center', va='bottom')
        plt.xticks(np.arange(len(order)), labels, ha='center', fontsize=12)
        plt.savefig(self._output_path + "/emotion_bar.png")
        if self._show:
            plt.show()
        plt.clf()

    # 按时间统计情感
    def time_line(self):
        sns.set_style('darkgrid')
        self._user_data['comment_date'] = self._user_data['comment_time'].dt.date
        time_line_data = self._user_data.groupby(['platform', 'comment_date']).size().reset_index(name='value')
        time_line_data['comment_date'] = time_line_data['comment_date'].astype(str)
        time_line_data = time_line_data.to_dict(orient='records')
        return {'time_line_data': time_line_data,
                'sum_data': self._user_data.groupby('platform').size().reset_index(name='value').to_dict(
                    orient='records')}
